<template>
    <el-dialog :title="title"
               :visible="dialogFormVisible"
               :close-on-click-modal="false">
        {{studentForm}}
        <el-form :model="studentForm" ref="studentFormRef" :rules="rules">
            <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                <el-input v-model="studentForm.sname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
                <el-select v-model="studentForm.sex" placeholder="请选择学生性别" style="width: 100%">
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                <el-input v-model.number="studentForm.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                <el-input v-model="studentForm.addr" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
                <el-select v-model="studentForm.cid" placeholder="请选择所在班级" style="width: 100%">
                    <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
    //导入操作班级的API方法
    import {findAllClasses} from '../../api/classes'
    //导入操作学生的API方法
    import {save} from "../../api/student";

    export default {
        name: "Student-Add-or-Update",
        data() {
            //自定义验证规则
            let checkAge = (rule, value, callback) => {
                if (!Number.isInteger(value)) {
                    return callback(new Error('年龄必须是整数!'));
                } else {             //这里一定要添加else的返回的回调
                    callback();
                }
            };
            return {
                title: '添加学生',
                dialogFormVisible: false,    //是否显示对话框
                studentForm: {sex:'男',cid:1},             //绑定的表单对象
                formLabelWidth: '120px',      //绑定表单中的label的宽度
                classes: [],                  //代表班级列表
                rules: {
                    //验证学生姓名
                    sname: [
                        {required: true, message: '请输入学生姓名', trigger: 'blur'},
                        {min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur'}
                    ],
                    sex: [
                        {required: true, message: '请选择学生性别', trigger: 'blur'},
                    ],
                    age: [
                        {required: true, message: '请输入学生年龄', trigger: 'blur'},
                        {validator: checkAge, trigger: 'blur'}
                    ],
                    addr: [
                        {required: true, message: '请输入学生住址', trigger: 'blur'},
                    ],
                    cid: [
                        {required: true, message: '请选择班级', trigger: 'blur'},
                    ]
                }
            }
        },
        methods: {
            //1.组件初始化方法
            init(row) {
                //1.1 显示当前的对话框
                this.dialogFormVisible = true;
                //1.2 重置表单
                this.studentForm = {};
                //1.2 如果row有值，代表是修改操作
                if (row) {
                    this.title = "修改学生";
                    this.studentForm = row;
                }

            },
            //7.查询所有班级列表
            findAllClasses() {
                findAllClasses().then(({data: res}) => {
                    console.log(res);
                    this.classes = res;
                })

            },
            //8.保存学生(添加或修改)
            save() {
                //8.1 定义url地址
                let url = "/student?cmd=add";       //代表添加
                //8.2 如果有sid的话，就是修改操作
                if (this.studentForm.sid) {
                    url = "/student?cmd=update";    //代表修改
                }
                this.$refs.studentFormRef.validate(async valid => {
                    if (valid) {       //代表所有表单控件验证通过
                        const {data: rs} = await save(url, "stud=" + JSON.stringify(this.studentForm));
                        if (rs.success) {      //刷新页面
                            this.$message({
                                message: "保存学生成功",
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    //关闭对话框
                                    this.dialogFormVisible = false;
                                    //刷新页面，触发父组件的事件[重点]
                                    this.$emit("refreshStudentData");
                                }
                            })

                        } else {
                            this.$message.error("保存学生失败！")
                            //关闭对话框
                            this.dialogFormVisible = false;
                        }
                    }
                })
            },
        },
        created() {
            this.findAllClasses();
        }
    }
</script>
